<template>
  <div style="width: 100%;" class="card-area">
    <layout-content topTitle="查询" bottomTitle="字典列表">
      <!-- 搜索区域 -->
      <template v-slot:topCard>
        <search-view ref="searchView" @search="search"></search-view>
      </template>
      <!-- 额外操作，在右侧 -->
      <template v-slot:extraOperation>
        <a-button class="extra-btn" type="primary" @click="handleOperationClick('add')">
          新增
        </a-button>
      </template>
      <!-- 表格区域 -->
      <template v-slot:bottomCard>
        <a-table
          ref="TableInfo"
          :columns="columns"
          rowKey="dictId"
          :dataSource="dataSource"
          :pagination="pagination"
          :loading="loading"
          :scroll="{ x: 1300 }"
          @change="handleTableChange"
        >
          <template slot="status" slot-scope="text">
            <span :style="{ color: text === '0' ? '#1890ff' : '#ff0000' }">{{ statusMap[text] }}</span>
          </template>
          <template slot="operation" slot-scope="text, record">
            <a-button type="link" @click="handleOperationClick('edit',record)" class="icon">修改</a-button>
            <a-button
              v-if="record.status === '0'"
              type="link"
              class="icon"
              style="padding-left:10px"
              @click="onApproval(record.dictId, 1)"
            >停用
            </a-button>
            <a-button
              v-if="record.status === '1'"
              type="link"
              @click="onApproval(record.dictId, 0)"
              class="icon"
              style="padding-left:10px"
            >启用
            </a-button>
            <a-button
              type="link"
              @click="onDelete(record)"
              class="icon"
              style="padding-left:10px"
            >删除
            </a-button>
          </template>
        </a-table>        <!-- 新增 -->
        <add-record
          :addOrEdit="addOrEdit"
          :key="addKey"
          :visible="addVisible"
          :initRecord="selectedRecord"
          :dictDataList="dictDataList"
          @close="addClose"
          @success="onAddSuccess"
          :apiURL="apiURL"
        ></add-record>
      </template>
    </layout-content>
  </div>
</template>

<script>
import columns from './colunms';
import apiURL from './requestURL';
import searchView from './search-view';
import addRecord from './add';
import layoutContent from '@/components/tool/layout-content';

const formItemLayout = {
  labelCol: {span: 4},
  wrapperCol: {span: 19}
};

export default {
  name: "main",
  components: {searchView, addRecord, layoutContent},
  data() {
    return {
      // 添加或编辑
      addOrEdit: 0,
      // 组件渲染的key
      addKey: new Date().getTime(),
      params: {},
      columns,  // 表头字段
      apiURL, // 接口url
      // 组件的可见性
      addVisible: false,
      // 当前选中的记录
      selectedRecord: {},
      dataSource: [],
      //字典数据
      dictDataList: [],
      sortedInfo: null,
      paginationInfo: null,
      pagination: {
        size: 'small',
        pageSizeOptions: ['10', '20', '30', '40', '100'],
        defaultCurrent: 1,
        defaultPageSize: 10,
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal: (total, range) => `显示 ${range[0]} ~ ${range[1]} 条记录，共 ${total} 条记录`
      },
      loading: false,
      statusMap: Object.freeze({
        '0': '正常',
        '1': '停用'
      }),
    }
  },
  created() {
    this.fetch();
  },
  mounted() {
  },
  methods: {

    // 1.查询记录
    fetch(params = {}) {
      this.loading = true;
      if (this.paginationInfo) {
        // 如果分页信息不为空，则设置表格当前第几页，每页条数，并设置查询分页参数
        this.$refs.TableInfo.pagination.current = this.paginationInfo.current;
        this.$refs.TableInfo.pagination.pageSize = this.paginationInfo.pageSize;
        params.pageSize = this.paginationInfo.pageSize;
        params.pageNum = this.paginationInfo.current;
      } else {
        // 如果分页信息为空，则设置为默认值
        params.count = this.pagination.defaultPageSize;
        params.currentPage = this.pagination.defaultCurrent;
      }
      this.$get(apiURL.getRecords, {
        ...params
      }).then(r => {
        let data = r.data.data;
        let pagination = {...this.pagination};
        pagination.total = data.total;
        this.dataSource = data.rows;
        this.pagination = pagination;
        this.loading = false;
      }).catch(e => {
        console.error(e);
        this.loading = false;
      });
    },
    // 2.搜索
    search(params = {}) {
      this.params = params;
      let {sortedInfo} = this;
      let sortField, sortOrder;
      // 获取当前列的排序和列的过滤规则
      if (sortedInfo) {
        sortField = sortedInfo.field;
        sortOrder = sortedInfo.order;
      }
      this.fetch({
        ...params,
        sortField: sortField,
        sortOrder: sortOrder
      });
    },
    // 3.正常 停用
    onApproval(dictId, status) {
      let that = this;
      let op = status === 0 ? '启用' : '停用'
      this.$confirm({
        title: '提示?',
        content: `确定${op}吗？`,
        centered: true,
        onOk() {
          that.$post(apiURL.changStatus, {dictId, status}).then(() => {
            that.$message.success(`${op}成功`);
            that.search(that.params);
          });
        },
        onCancel() {
        }
      });
    },
    // 4.删除记录
    onDelete(record) {
      let that = this;
      this.$confirm({
        title: '确定删除吗?',
        content: '删除将不能恢复哦！',
        centered: true,
        onOk() {
          that.$post(apiURL.deleteRecord, {dictId: record.dictId}).then(() => {
            that.$message.success('删除成功');
            that.search(that.params);
          });
        },
        onCancel() {
        }
      });
    },
    // 5.新增/修改
    handleOperationClick(key, record = {}) {

      console.log(record)
      console.log(12321)
      this.addOrEdit = key === 'add' ? 0 : 1;

      if (this.addOrEdit === 0) {
        this.$set(record,'dictDataList', [
          {
            dictCode: undefined,
            dictSort: undefined,
            dictLabel: undefined,
            dictValue: undefined,
            dictType: undefined,
            isDefault: undefined,
            status: undefined,
            remark: undefined,
            createTime: undefined,
            modifyTime: undefined,
          }
        ])
        this.selectedRecord = record;
        this[`addKey`]++;
        this.addVisible = true;
      } else {
        this.$get(this.apiURL.getDataRecords, {dictType: record.dictType}).then(r => {
          this.$set(record,'dictDataList',r.data.data.rows)
          this.$set(record,'status',parseInt(record.status));
          this.selectedRecord = record;
          this[`addKey`]++;
          this.addVisible = true;
        }).catch(e => {
          console.error(e);
        })
      }


    },
    // 6.操作成功
    onAddSuccess() {
      this.addVisible = false;
      this.$message.success('操作成功');
      this.search(that.params);
      // this.search();
      // this.$refs['searchView'].handleSearch();
    },
    addClose(){
      this.search();
      this.addVisible=false;
    },
    //勾选
    handleTableChange() {

    },
  }

}
</script>
<style lang="less" scoped>
.code-img {
  width: 50px !important;
  margin: 10px 2px;
}

.icon {
  padding: 0;
  border: none;
  color: #1890ff;
}

.card-area {
  .extra-btn {
    width: 86px;
  }
}

.search-btn {
  margin-top: 8px;
}

.border-span {
  width: 2px;
  background-color: #cfd7de;
  height: 16px;
  margin-right: 2px;
  display: inline-block;
}
</style>
